<template>
  <div class="comment">
    <van-field
      class="my-field"
      v-model="message"
      rows="2"
      autosize
      label="发表评论"
      type="textarea"
      maxlength="50"
      placeholder="请输入bb的内容"
      show-word-limit
      ref="fieldRef"
    />
    <van-button
      class="post-comment"
      type="primary"
      block
      @click="postComment"
      >提交评论</van-button
    >
    <van-card
      v-for="(item, index) in comments"
      :key="index"
      :desc="item.content"
      title="商品标题"
    >
      <template #thumb>
        <div class="user">
          <van-icon
            class="user-icon"
            name="https://b.yzcdn.cn/vant/icon-demo-1126.png"
          />
          <div>匿名用户</div>
        </div>
      </template>
      <template #title>
        <van-rate
          v-model="item.rate"
          readonly
        />
      </template>
      <template #price>
        {{ item.add_time }}
      </template>
    </van-card>
    <van-loading
      size="24px"
      v-if="isLoading"
      >加载中...</van-loading
    >
    <button
      class="more"
      v-else
      @click="getMore"
    >
      {{ moreText }}
    </button>
  </div>
</template>
<script>
import moment from 'moment';
export default {
  props: ['id'],
  data() {
    return {
      isLoading: false,
      page: 0,
      limit: 30,
      comments: [],
      message: '',
      hasMore: false,
    };
  },
  created() {
    this.getComments();
  },
  methods: {
    async getComments() {
      if (this.hasMore !== false) return;
      ++this.page;
      const res = await this.$http.getComments({ id: this.id, page: this.page, limit: this.limit });
      // this.comments = this.comments.concat(res.data.message);
      this.comments = [...this.comments, ...res.data.message];
      this.hasMore = this.page * this.limit > res.data.count;
      console.log(this.hasMore);
    },
    async postComment() {
      await this.$http.postComment(this.id, this.message);
      this.comments.unshift({
        user_name: '匿名用户',
        add_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        content: this.message,
        rate: 5,
      });
      this.message = '';
      this.$refs.fieldRef.focus();
    },
    getMore() {
      this.isLoading = true;
      setTimeout(async () => {
        await this.getComments();
        this.isLoading = false;
      }, 500);
    },
  },
  computed: {
    moreText() {
      return this.hasMore ? '我也是有底线的' : ' 加载更多';
    },
  },
};
</script>
<style lang="scss" scoped>
.comment {
  .my-field {
    border: 1px solid #eee;
  }
  .post-comment {
    margin: 6px 0;
  }
  .user {
    .user-icon {
      font-size: 60px;
    }
  }
  .van-card__desc {
    margin-top: 15px;
  }
  .more {
    width: 100%;
    outline: none;
    border: 0;
    background-color: #fff;
    font-size: 12px;
    color: #969799;
  }
  .van-loading {
    text-align: center;
  }
}
</style>
